package org.alanlau.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.alanlau.zuul.base.ResponseCode;
import org.alanlau.zuul.base.ResponseData;
import org.alanlau.zuul.util.IpUtils;
import org.alanlau.zuul.util.JsonUtils;
import org.apache.commons.lang.StringUtils;

import java.util.Arrays;
import java.util.List;

/**
 * IP黑名单过滤
 *
 * @author alan
 * @version 1.0
 * @date 2020/9/19 14:16
 */
public class IpFilter extends ZuulFilter {
    /**
     * IP黑名单列表
     */
    private List<String> blackIpList = Arrays.asList("127.0.0.1");

    public IpFilter() {
        super();
    }

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        String ip = IpUtils.getIpAddr(context.getRequest());
        // 在黑名单中禁用
        if(StringUtils.isNotBlank(ip) && blackIpList.contains(ip)) {
            context.setSendZuulResponse(false);
            ResponseData data = ResponseData.fail(" 非法请求 ", ResponseCode.NO_AUTH_CODE.getCode());
            context.setResponseBody(JsonUtils.toJson(data));
            context.getResponse().setContentType("application/json;charset=utf-8");
        }
        return null;
    }
}
